#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# Magpie - an open source discussion forum system.
#
# Copyright (C) 2009 The Magpie Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import cgi

from ajiaojr.commons.django.shortcuts import render_to_response

from ajiaojr.magpie import models
from ajiaojr.magpie.views import build_template_params
from ajiaojr.magpie.views import club_enabled_required
from ajiaojr.magpie.views import club_writable_required
from ajiaojr.magpie.views.services.bank import bank_enabled_required

from django.http import HttpResponseForbidden
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _

from google.appengine.ext import db

def mine_game_enabled_required(func):
  """Decorator to ensure that the mine game is enabled
  """
  def mine_game_enabled_wrapper(request, *args, **kwds):
    config = models.MineGoldConfig.get_instance()
    if not config.is_enabled and not request.admin_mode:
      return HttpResponseForbidden("<h1>Access Denied</h1>")
    return func(request, *args, **kwds)
  return mine_game_enabled_wrapper

@club_enabled_required
@mine_game_enabled_required
def index(request):
  p = build_template_params(_('Mine Gold'), '/', request.user)
  return render_to_response(request, 'games/mine/index.html', p)

@club_writable_required
@mine_game_enabled_required
@bank_enabled_required
def dig(request, forward_url):
  user = request.user
  
  gms_key = 'gms:' + user.key().name()
  
  gms = models.GoldMiningStats.get_by_key_name(gms_key)
  if gms is None:
    gms = models.GoldMiningStats(key_name = gms_key,
                                 club_user = user,
                                 amount = 0,
                                 gms_index = user.key().name())
    
  gms.amount += 100
  gms.count += 1
  
  user.mine_dropped = False
  
  user.get_bank_account().deposit(100, _('Reward from mining'))
  db.put([user, gms])
  
  p = build_template_params(_('Congratulations'), '/', user)
  p['forward_url'] = forward_url
  return render_to_response(request, 'games/mine/dig.html', p)
